<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Advert;
use app\common\model\Category;
use app\common\model\Give;
use app\common\model\Goods as Goodsmodel;
use app\common\model\GoodsList;
use app\common\model\Order;
use app\common\model\OrderList;
use app\common\model\Shang;
use app\common\model\UserVip;
use think\facade\Db;
use think\Request;

class Cardextractor extends Base
{

    /**
     * 抽卡机首页
     */
    public function cardextractor_index(Request $request)
    {
        #抽卡机轮播图
        $advert = Advert::field('imgurl')->where(['type' => 2])->order('sort desc,id desc')->select();
        foreach ($advert as &$advert_value) {
            $advert_value['imgurl'] = imageUrl($advert_value['imgurl']);
        }
        #分类
        $category = Category::field('id,title')->order('sort desc,id asc')->select()->toArray();
        array_unshift($category, ['id' => 0, 'title' => '全部IP']);
        #弹幕
        $new_bulletcha = [];
        $bulletchat = OrderList::field('id,user_id,goods_id,goodslist_title')
            ->append(['user_info', 'goods_title'])
            ->where('order_type', '=', 4)
            ->order('id desc')
            ->limit(20)
            ->select();
        foreach ($bulletchat as $bulletchat_value) {
            $user_info = $bulletchat_value['user_info'];
            $goods_title = $bulletchat_value['goods_title'];
            $goodslist_title = $bulletchat_value['goodslist_title'];
            $new_bulletcha[] = [
                'headimg' => $user_info['headimg'],
                'content' => $user_info['nickname'] . ' 抽中了 [' . $goods_title . '] 中的 ' . $goodslist_title,
            ];
        }
        $new_data = [
            'advert' => $advert,
            'category' => $category,
            'new_bulletcha' => $new_bulletcha,
        ];
        return $this->renderSuccess('请求成功', $new_data);
    }

    /**
     * 抽卡机奖品
     */
    public function cardextractor_goods(Request $request)
    {
        $keyword = request()->param('keyword', '');
        $category_id = request()->param('category_id/d', 0);
        $whe = [];
        $whe[] = ['status', '=', 1];
        $whe[] = ['type', '=', 4];
        #搜索
        if ($keyword) {
            $whe[] = ['title', 'like', '%' . $keyword . '%'];
        }
        #分类
        if ($category_id > 0) {
            $whe[] = ['category_id', '=', $category_id];
        }
        #盒子
        $goods = GoodsModel::where($whe)
            ->field("id,title,imgurl,price,show_price,type,stock,sale_stock,status,card_set")
            ->order("sort desc,id desc")->paginate(15)->each(function ($itme) {
//                $card_set = json_decode($itme['card_set'], true);
//                $itme['price'] = bcmul("{$itme['price']}", "{$card_set['left_count']}", 2);
                $itme['price'] = $itme['show_price'];
                $itme['imgurl'] = imageUrl($itme['imgurl']);
                unset($itme['card_set']);
                #参与人数
                $join_user = OrderList::field('user_id')
                    ->append(['userinfo'])
                    ->where('goods_id', '=', $itme['id'])
                    ->where('order_type', '=', 4)
                    ->order('id desc')
                    ->group('user_id')
                    ->limit(10)
                    ->select();
                $new_join_user = [];
                foreach ($join_user as $join_user_value) {
                    $new_join_user[] = $join_user_value['userinfo']['headimg'];
                }
                $itme['join_user'] = $new_join_user;
                #参与次数
                $join_count = OrderList::field('id')->where('goods_id', '=', $itme['id'])->where('order_type', '=', 4)->count();
                $itme['join_count'] = $join_count;
            });
        $new_data = [
            'data' => $goods->items(),
            'last_page' => $goods->lastPage(),
        ];
        return $this->renderSuccess('请求成功', $new_data);
    }

    /**
     * 抽卡机盒子详情
     */
    public function cardextractor_goodsdetail()
    {
        $user_info = $this->getUser();
        $goods_id = request()->param('goods_id/d', 0);
        $goods = Goodsmodel::field('id,title,card_notice,imgurl_detail,card_banner,price,show_price,type,status,card_set,addtime')
            ->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }

        $goods['addtime'] = date('Y-m-d H:i:s', $goods['addtime']);
        $goods['imgurl_detail'] = imageUrl($goods['imgurl_detail']);
        $goods['card_banner'] = imageUrl($goods['card_banner']);
        $card_set = json_decode($goods['card_set'], true);
//        $goods['price'] = bcmul("{$goods['price']}", "{$card_set['left_count']}", 2);
        $goods['price'] = $goods['show_price'];
        unset($card_set['left_shang_id']);
        unset($card_set['left_shang_count']);
        unset($card_set['center_shang_id']);
        unset($card_set['center_shang_count']);
        unset($card_set['right_shang_id']);
        unset($card_set['right_shang_count']);
        $goods['card_set'] = $card_set;
        return $this->renderSuccess("请求成功", $goods);
    }

    /**
     * 抽卡机盒子图鉴
     */
    public function cardextractor_goodslist_log()
    {
        $shang_id = request()->param('shang_id/d', 0);
        $goods_id = request()->param('goods_id/d', 0);
        $goods = Goodsmodel::field('id,title,status')
            ->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        #奖品图鉴
        $category = Shang::field('id,title,pro')
            ->where('goods_id', '=', $goods_id)
            ->withAttr('pro', function ($value, $data) {
                return '概率:' . ($value * 1) . '%';
            })
            ->order('sort desc,id asc')
            ->select()->toArray();
//        array_unshift($category, ['id' => 0, 'title' => '全部', 'pro' => 0]);
        $where = [];
        if ($shang_id) {
            $where[] = ['shang_id', '=', $shang_id];
        } else {
            $where[] = ['shang_id', '=', $category[0]['id']];
        }
        $data = GoodsList::field('title,imgurl,shang_id,price,real_pro')
            ->withAttr('imgurl', function ($value, $data) {
                return imageUrl($value);
            })
            ->append(['shang_info'])
            ->where('goods_id', '=', $goods_id)
            ->where('num', '=', 0)
            ->where($where)
            ->paginate(12);
        $goodslist = $data->items();
        $last_page = $data->lastPage();
        foreach ($goodslist as &$value) {
            $value['price'] = '参考价:' . $value['price'] . '元';
            $value['real_pro'] = '组内概率:' . ($value['real_pro'] * 1) . '%';
            $value['shang_title'] = $value['shang_info']['title'];
            $value['shang_imgurl'] = $value['shang_info']['imgurl'];
            unset($value['shang_info']);
        }
        $new_data = [
            'category' => $category,
            'goodslist' => $goodslist,
            'last_page' => $last_page,
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }

    /**
     * 中赏记录
     */
    public function cardextractor_shang_log(Request $request)
    {
        $shang_id = request()->param('shang_id/d', 0);
        $goods_id = request()->param('goods_id/d', 0);
        #盒子信息
        $goods = Goodsmodel::field('id,stock,status,type')
            ->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        #奖品图鉴
        $category = Shang::field('id,title')
            ->where('goods_id', '=', $goods_id)
            ->order('sort desc,id asc')
            ->select()->toArray();
//        array_unshift($category, ['id' => 0, 'title' => '全部']);
        $where = [];
        if ($shang_id) {
            $where[] = ['shang_id', '=', $shang_id];
        } else {
            $where[] = ['shang_id', '=', $category[0]['id']];
        }
        $data = OrderList::field('user_id,goodslist_title,goodslist_imgurl,shang_id,addtime,count(`id`) as prize_num')
            ->append(['shang_title', 'user_info'])
            ->where('goods_id', '=', $goods_id)
            ->where('num', '=', 0)
            ->where('order_type', '=', $goods['type'])
            ->where($where)
            ->group("order_id,goodslist_id")
            ->order('id desc')
            ->paginate(15)->each(function ($item) {
                $item['nickname'] = $item['user_info']['nickname'];
                $item['headimg'] = $item['user_info']['headimg'];
                $item['addtime'] = date('Y-m-d H:i:s', $item['addtime']);
                $item['goodslist_imgurl'] = imageUrl($item['goodslist_imgurl']);
                return $item;
            });
        $new_data = [
            'category' => $category,
            'data' => $data->items(),
            'last_page' => $data->lastPage(),
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }


    /**
     * 下单计算金额
     */
    public function cardextractor_ordermoney()
    {
        $user = $this->getUser();
        $goods_id = request()->param('goods_id/d', 0);               #盒子ID
        $prize_num_type = request()->param('prize_num_type', '');    #抽奖发数类型
        $use_money_is = request()->param('use_money_is/d', 0);       #0不抵扣 1抵扣
        $use_integral_is = request()->param('use_integral_is/d', 0); #0不抵扣 1抵扣
        #盒子信息
        $goods = Goodsmodel::field('title,type,price,status,card_set')
            ->where(['id' => $goods_id])
            ->find();
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        if ($prize_num_type != 'left_count' && $prize_num_type != 'center_count' && $prize_num_type != 'right_count') {
            return $this->renderError("请求参数错误");
        }
        #抽数配置
        $card_set = json_decode($goods['card_set'], true);
        if (!isset($card_set[$prize_num_type])) {
            return $this->renderError("配置错误,请联系管理员");
        }
        unset($goods['card_set']);
        $prize_num = $card_set[$prize_num_type];
        #盒子单价
        $box_price = $goods['price'];
        #订单金额 微信支付金额
        $order_total = $order_zhe_total = $price = bcmul("$box_price", "$prize_num", 2);
        $zhe = 0;
        $vip_info = UserVip::where(['id' => $user['vip']])->find();
        if ($vip_info && $vip_info['discount'] > 0) {
            $zhe = $vip_info['discount'];
            $zhe_bl = bcdiv("$zhe", "10", 2);
            $order_zhe_total = $price = bcmul("$price", "$zhe_bl", 2);
        }
        #潮币抵扣
        $use_integral = 0;
        if ($use_integral_is == 1) {
            if ($user['integral'] >= $price) {
                $use_integral = $price;
                $price = 0;
            } else {
                $use_integral = $user['integral'];
                $price = bcsub("$price", "{$user['integral']}", 2);
            }
        }
        #余额抵扣
        $use_money = 0;
        if ($use_money_is == 1) {
            if ($user['money'] >= $price) {
                $use_money = $price;
                $price = 0;
            } else {
                $use_money = $user['money'];#
                $price = bcsub("$price", "{$user['money']}", 2);
            }
        }
        #抽奖数量
        $goods['prize_num'] = $prize_num;
        $data = [
            'goods' => $goods,
            'order_total' => $order_total * 1,
            'order_zhe_total' => $order_zhe_total * 1,
            'zhe' => ($zhe * 1),
            'price' => $price * 1,
            'integral' => $user['integral'] * 1,
            'use_integral' => $use_integral * 1,
            'money' => $user['money'] * 1,
            'use_money' => $use_money * 1,
        ];
        return $this->renderSuccess("请求成功", $data);
    }

    /**
     * 下单购买
     */
    public function cardextractor_orderbuy()
    {
        $user = $this->getUser();
        if (empty($user['mobile'])) {
            return $this->renderError('请先绑定手机号', [], -9);
        }
        $goods_id = request()->param('goods_id/d', 0);               #盒子ID
        $prize_num_type = request()->param('prize_num_type', '');    #抽奖发数类型
        $use_money_is = request()->param('use_money_is/d', 0);       #0不抵扣 1抵扣
        $use_integral_is = request()->param('use_integral_is/d', 0); #0不抵扣 1抵扣
        #盒子信息
        $goods = Goodsmodel::field('id,title,card_banner,type,price,status,card_set, max_num')->where(['id' => $goods_id])
            ->find();
                  //开盒成功减限制
        $where = [];
        $where[] = ['user_id', '=', $user['id']];
        $where[] = ['goods_id', '=', $goods_id];
        $order_count = OrderList::where($where)->field('id')->count('id');
        if ( $goods['max_num'] > 0 and $order_count >= $goods['max_num']) {
            return $this->renderError("已达上限");
        }
        if (!$goods) {
            return $this->renderError("盒子不存在");
        }
        if ($goods['status'] != 1) {
            return $this->renderError("盒子已下架");
        }
        if ($goods['type'] != 4) {
            return $this->renderError("非法请求");
        }

        #卡等级随机
        $is_shang = Shang::field('id')
            ->where('goods_id', '=', $goods_id)
            ->where('pro', '>', 0)
            ->find();
        if (!$is_shang) {
            return $this->renderError('暂无奖品信息!!!');
        }
        #奖品信息
        $is_goodslist = GoodsList::field('id')
            ->where('goods_id', '=', $goods_id)
            ->where('num', '=', 0)
            ->where('real_pro', '>', 0)
            ->where('special_stock', '<>', 0)
            ->find();
        if (!$is_goodslist) {
            return $this->renderError('暂无奖品信息');
        }
        #抽数配置
        $card_set = json_decode($goods['card_set'], true);
        if (!isset($card_set[$prize_num_type])) {
            return $this->renderError("配置错误,请联系管理员");
        }
        $prize_num = $card_set[$prize_num_type];
        $prize_card_set = NULL;
        if ($prize_num_type == 'left_count') {
            $pre_type = 'left';
        } elseif ($prize_num_type == 'center_count') {
            $pre_type = 'center';
        } elseif ($prize_num_type == 'right_count') {
            $pre_type = 'right';
        } else {
            return $this->renderError("请求参数错误!!!");
        }
        $key_shang_id = $pre_type . '_shang_id';
        $key_shang_count = $pre_type . '_shang_count';
        
        if (isset($card_set[$key_shang_id]) && isset($card_set[$key_shang_count])) {
            $prize_card_set = json_encode([
                'shang_id' => $card_set[$key_shang_id],
                'shang_count' => $card_set[$key_shang_count],
            ]);
        }
        #盒子单价
        $box_price = $goods['price'];
        #订单金额 微信支付金额
        $order_total = $order_zhe_total = $price = bcmul("$box_price", "$prize_num", 2);
        #折扣
        $zhe = 0;
        $vip_info = UserVip::where(['id' => $user['vip']])->find();
        if ($vip_info && $vip_info['discount'] > 0) {
            $zhe = $vip_info['discount'];
            $zhe_bl = bcdiv("$zhe", "10", 2);
            $order_zhe_total = $price = bcmul("$price", "$zhe_bl", 2);
        }
        #潮币抵扣
        $use_integral = 0;
        if ($use_integral_is == 1) {
            if ($user['integral'] >= $price) {
                $use_integral = $price;
                $price = 0;
            } else {
                $use_integral = $user['integral'];
                $price = bcsub("$price", "{$user['integral']}", 2);
            }
        }
        #余额抵扣
        $use_money = 0;
        if ($use_money_is == 1) {
            if ($user['money'] >= $price) {
                $use_money = $price;
                $price = 0;
            } else {
                $use_money = $user['money'];#
                $price = bcsub("$price", "{$user['money']}", 2);
            }
        }

        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis_key = "kpw_cardextractor_orderbuy" . '_' . $user['id'];
        $redis_key_info = $redis->get($redis_key);
        if ($redis_key_info) {
            return $this->renderError("当前操作太快了,请等待");
        } else {
            $redis->set($redis_key, 1, 10);
        }
        Db::startTrans();
        $res = [];
        $order_num = create_order_no('MH_', 'order', 'order_num');
        #创建订单
        $res[] = $order_id = Order::insertGetId([
            'user_id' => $user['id'],
            'order_num' => $order_num,
            'order_total' => $order_total,#订单金额
            'order_zhe_total' => $order_zhe_total,#订单折扣金额
            'price' => $price,#微信支付
            'use_money' => $use_money,#余额抵扣
            'use_integral' => $use_integral,#潮币抵扣
            'use_score' => 0,#积分抵扣
            'zhe' => $zhe,#会员折扣
            'goods_id' => $goods_id,
            'num' => 0,
            'goods_price' => $goods['price'],
            'goods_title' => $goods['title'],
            'goods_imgurl' => $goods['card_banner'],
            'prize_num' => $prize_num,
            'prize_card_set' => $prize_card_set,
            'status' => 0,
            'pay_type' => 1,#1微信 2支付宝
            'order_type' => $goods['type'],
            'addtime' => time(),
        ]);
        #微信支付金额大于0
        if ($price > 0) {
            $body = '购买盒子' . $goods['title'];
            $attach = 'order_ckj';
            $payRes = (new Pay())->wxCreateOrder($order_num, $price, $user['openid'], $body, $attach);
            if ($payRes['status'] == 1) {
                #结果集
                $new_data = [
                    'status' => 1,
                    'order_num' => $order_num,
                    'res' => $payRes['data'],
                ];
            } else {
                #删除redis
                $redis->del($redis_key);
                Db::rollback();
                return $this->renderError("下单失败");
            }
        } else {
            #开盒子
            $res[] = (new Notify($this->app))->cardextractor_drawprize_notice($user['id'], $order_id, $goods_id);
            #结果集
            $new_data = [
                'status' => 0,
                'order_num' => $order_num,
            ];
            
        }
        if (resCheck($res)) {
            
            Db::commit();
            #删除redis
            $redis->del($redis_key);
            return $this->renderSuccess("下单成功", $new_data);
        } else {
            Db::rollback();
            #删除redis
            $redis->del($redis_key);
            return $this->renderError("购买失败,请刷新重试");
        }
    }


    /**
     * 抽中的奖品
     */
    public function cardextractor_prizeorderlog()
    {
        $user = $this->getUser();
        $order_num = request()->param('order_num', '');
        $order_info = Order::field('id,goods_id,num,order_type')
            ->where('order_num', '=', $order_num)
            ->where('user_id', '=', $user['id'])
            ->where('status', '=', 1)
            ->find();
        if (!$order_info) {
            return $this->renderError("支付异常,请刷新重试");
        }
        #背面图
        $prize_imgurl = Goodsmodel::field('prize_imgurl')->where('id', '=', $order_info['goods_id'])->value('prize_imgurl');
        $prize_imgurl = imageUrl($prize_imgurl);
        #普通赏
        $data = OrderList::field('user_id,shang_id,goodslist_id,goodslist_title,goodslist_imgurl,count(id) as prize_num')
            ->append(['shang_title', 'special_imgurl'])
            ->where('user_id', '=', $user['id'])
            ->where('order_id', '=', $order_info['id'])
            ->where('order_type', '=', $order_info['order_type'])
            ->order('id desc')
            ->group("prize_code")
            ->select()->toArray();
        foreach ($data as &$value) {
            $value['goodslist_imgurl'] = imageUrl($value['goodslist_imgurl']);
            $value['prize_imgurl'] = $prize_imgurl;
        }
        $new_data = [
            'user_info' => [
                'nickname' => $user['nickname'],
                'headimg' => $user['headimg'],
            ],
            'data' => $data,
        ];
        return $this->renderSuccess("请求成功", $new_data);
    }


}
